package cn.jingyuan.swan.hello.web.controller;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RefreshScope
@RestController
public class IndexController {

    @Resource
    Environment env;

    @Resource
    DiscoveryClient discoveryClient;

    @GetMapping("/name")
    public Object name() {

        Map<String, Object> map = new HashMap<>(2);
        map.put("name", env.getProperty("name"));
        map.put("app-version", env.getProperty("app-version"));

        return map;
    }

    @GetMapping("/app")
    public Object app() {
        List<String> services = discoveryClient.getServices();
        List<Map<String, String>> list = new ArrayList<>();
        for (String service : services) {
            List<ServiceInstance> instances = discoveryClient.getInstances(service);
            for (ServiceInstance instance : instances) {
                list.add(instance.getMetadata());
            }
        }
        return list;
    }

}
